import React, {
  ReactElement,
  useState,
  useEffect,
  useImperativeHandle,
  forwardRef,
} from 'react'
import {
  Row,
  Col,
  Form,
  Input,
  DatePicker,
  Button,
  Select,
  InputNumber,
} from 'antd'
import style from '../index.less'
import commonStyle from '@/pages/publicStyle'
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons'
import moment from 'moment'
import UploadCom from '@/components/UploadCom'
import { FormType, VoteObject } from '../..'
import { dataFormat2 } from '@/untils/dictionaries'

const RangePicker: any = DatePicker.RangePicker
const { Option } = Select
const layout = {
  labelCol: { span: 24 },
  wrapperCol: { span: 14 },
}
// 上传图片表单专属大小
const tailLayout = {
  wrapperCol: { offset: 0, span: 4 },
}

interface IProps {
  VoteData: any
  saveFormData: () => void
  isDrop: boolean
}
const Vote = forwardRef((props: IProps, ref: any): ReactElement => {
  const [form] = Form.useForm()
  const [VoteObjectVOS, setVoteObjectVOS] = useState<VoteObject[]>([
    {
      name: '',
      instructions: '',
      pictureKey: '',
      pictureUrl: '',
    },
  ])
  const [submitForm, setSubmitForm] = useState<FormType>({
    activityType: '2',
    startDate: '',
    endDate: '',
    dayVoteLimit: 1,
    singlePlayerLimit: 1,
    voteWay: '',
  })
  // 修改活动日期
  const activityTimeChange = (dataString: string[]) => {
    let oldFormData = JSON.parse(JSON.stringify(submitForm))
    oldFormData.startDate = dataString[0]
    oldFormData.endDate = dataString[1]
    setSubmitForm(oldFormData)
  }
  // 增加投票对象
  const addVoteObject = () => {
    setVoteObjectVOS([
      ...VoteObjectVOS,
      {
        name: '',
        instructions: '',
        pictureKey: '',
        pictureUrl: '',
      },
    ])
  }
  // 删除投票对象
  const removeVoteObject = (index: number) => {
    setVoteObjectVOS(VoteObjectVOS.filter((item, vindex) => vindex !== index))
  }
  const inputChangeVOS = (value: string, filedName: string, index: number) => {
    const oldVOSData = JSON.parse(JSON.stringify(VoteObjectVOS))
    oldVOSData[index][filedName] = value
    setVoteObjectVOS(oldVOSData)
  }
  // 活动图图片上传
  const imgUploadSuccess = (imgData: any, index: number) => {
    let oldVOSData = JSON.parse(JSON.stringify(VoteObjectVOS))
    oldVOSData[index].pictureUrl = imgData.imgUrl
    oldVOSData[index].pictureKey = imgData.imgKey
    setVoteObjectVOS(oldVOSData)
  }
  // 活动图片初始化
  const initUploadImg = (ref: any, index: number) => {
    if (ref) {
      if (
        index <= VoteObjectVOS.length - 1 &&
        VoteObjectVOS[index].pictureUrl
      ) {
        ref.initImgSrc(VoteObjectVOS[index].pictureUrl)
      }
    }
  }
  // 图片验证
  const pictureUpCheck = (callback: any, index: number) => {
    try {
      if (!VoteObjectVOS[index].pictureUrl) {
        return Promise.reject('请提交上传图片')
      } else {
        return Promise.resolve()
      }
    } catch (error) {
      callback(error)
    }
  }
  // 返回完成校验数据
  const getOverFormData = () => {
    return {
      ...submitForm,
      VoteObjectVOS,
    }
  }
  useImperativeHandle(ref, () => {
    return {
      form: form,
      getOverFormData: getOverFormData,
    }
  })
  // 初始化数据
  useEffect(() => {
    if (props.VoteData) {
      setTimeout(() => {
        const getData = JSON.parse(JSON.stringify(props.VoteData))
        const updateForm = {
          activityTime: [
            getData.startDate
              ? moment(getData.startDate, dataFormat2)
              : undefined,
            getData.endDate ? moment(getData.endDate, dataFormat2) : undefined,
          ],
          voteWay: getData.voteWay,
          dayVoteLimit: getData.dayVoteLimit,
          singlePlayerLimit: getData.singlePlayerLimit,
        }
        let listForm = getData?.VoteObjectVOS?.reduce(
          (updateData: any, item: any, index: number) => {
            updateData['instructions' + index] = item.instructions
            updateData['name' + index] = item.name
            return updateData
          },
          {},
        )
        form.setFieldsValue({ ...updateForm, ...listForm })
        setVoteObjectVOS(getData.VoteObjectVOS)
        delete getData.VoteObjectVOS
        setSubmitForm(getData)
      }, 0)
    }
  }, [])
  // 折叠时暂存数据
  useEffect(() => {
    return () => {
      if (!props.isDrop) {
        props.saveFormData(getOverFormData(), 'VoteData')
      }
    }
  }, [props.isDrop])
  const activityCheck = (rules: any, value: any, callback: any) => {
    try {
      if (submitForm.startDate && submitForm.endDate) {
        return Promise.resolve()
      } else {
        return Promise.reject('请选择活动日期')
      }
    } catch (error) {
      callback(error)
    }
  }
  const { detailFormTitle, formBorderBox } = style
  const { completeW, mt10, mt20, mt50 } = commonStyle
  return (
    <div>
      <Form {...layout} form={form}>
        <div className={detailFormTitle}>基本信息</div>
        <div className={formBorderBox}>
          <Row>
            <Col span={12}>
              <Form.Item
                name="activityTime"
                label="活动时间"
                rules={[{ required: true, validator: activityCheck }]}
              >
                <RangePicker
                  format={dataFormat2}
                  onChange={(dates: moment.Moment[], dateStrings: string[]) => {
                    activityTimeChange(dateStrings)
                  }}
                  showTime
                  style={completeW}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="voteWay"
                label="投票方式"
                rules={[{ required: true, message: '请选择投票方式' }]}
              >
                <Select
                  onChange={(value: string) => {
                    setSubmitForm({ ...submitForm, voteWay: value })
                  }}
                >
                  <Option value="1">只可投一次</Option>
                  <Option value="2">每日均可投</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          {submitForm.voteWay === '2' && (
            <Row>
              <Col span={12}>
                <Form.Item
                  name="dayVoteLimit"
                  label="单日可投上限"
                  rules={[{ required: true, message: '请输入单日可投上限' }]}
                >
                  <InputNumber
                    style={completeW}
                    min={1}
                    max={9999999}
                    formatter={value => `${Math.floor(value || 1)}`}
                    onChange={value => {
                      setSubmitForm({
                        ...submitForm,
                        dayVoteLimit: Number(value),
                      })
                    }}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="singlePlayerLimit"
                  label="重复投票上限"
                  rules={[{ required: true, message: '请输入重复投票上限' }]}
                >
                  <InputNumber
                    style={completeW}
                    min={1}
                    max={9999999}
                    formatter={value => `${Math.floor(value || 1)}`}
                    onChange={value => {
                      setSubmitForm({
                        ...submitForm,
                        singlePlayerLimit: Number(value),
                      })
                    }}
                  />
                </Form.Item>
              </Col>
            </Row>
          )}
        </div>
        <div className={detailFormTitle} style={mt20}>
          投票对象
        </div>
        {VoteObjectVOS?.map((item, index) => (
          <div className={formBorderBox} key={index}>
            <Row>
              <Col span={12}>
                <Form.Item
                  name={['instructions' + index]}
                  label="名称"
                  rules={[{ required: true, message: '请输入投票对象名称' }]}
                >
                  <Input
                    placeholder="请输入投票对象的名称"
                    onChange={(e: any) => {
                      inputChangeVOS(e.target.value, 'instructions', index)
                    }}
                  ></Input>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name={['name' + index]}
                  label="说明"
                  rules={[{ required: true, message: '请输入投票对象的说明' }]}
                >
                  <Input
                    placeholder="请输入投票对象的说明"
                    onChange={(e: any) => {
                      inputChangeVOS(e.target.value, 'name', index)
                    }}
                  ></Input>
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item
                  name="pictureUrl"
                  label="图片"
                  rules={[
                    {
                      required: true,
                      validator: (rules: any, value: any, callback: any) => {
                        return pictureUpCheck(callback, index)
                      },
                    },
                  ]}
                  {...tailLayout}
                >
                  <UploadCom
                    tagMessage="支持扩展名：jpg.jpeg.png"
                    isImgBtn={true}
                    UploadSuccess={(imgdata: any) => {
                      imgUploadSuccess(imgdata, index)
                    }}
                    ref={ref => {
                      initUploadImg(ref, index)
                    }}
                  ></UploadCom>
                </Form.Item>
              </Col>
              {index !== 0 && (
                <Col span={12} style={{ textAlign: 'right' }}>
                  <Button
                    onClick={() => {
                      removeVoteObject(index)
                    }}
                    style={mt50}
                    type="primary"
                    danger
                    shape="circle"
                    icon={<DeleteOutlined style={{ color: '#fff' }} />}
                    size="large"
                  />
                </Col>
              )}
            </Row>
          </div>
        ))}
        <Row style={mt10}>
          <Col span={24}>
            <Button
              style={completeW}
              type="dashed"
              icon={<PlusOutlined />}
              onClick={() => {
                addVoteObject()
              }}
            >
              添加
            </Button>
          </Col>
        </Row>
      </Form>
    </div>
  )
})
export default Vote
